/**
 * @author: sundx
 * @date: 2020-06-08 01:17:11
 * @Last Modified by: sundx
 * @Last Modified time: 2020-06-08 01:17:39
 */
#include "http_conn.h"

int http_conn::epollFd = -1;
int http_conn::myUserCnt = 0;
http_conn::http_conn() {}

http_conn::~http_conn() {}

// 接受新连接
void http_conn::init(int sockFd, const struct sockaddr_in &addr) {

  m_socketFd = sockFd;
  clientAddr = addr;
  char clientAddrChar[INET_ADDRSTRLEN];
  std::cout << "new client "
            << inet_ntop(AF_INET, &clientAddr.sin_addr, clientAddrChar,
                         INET_ADDRSTRLEN)
            << " " << ntohs(clientAddr.sin_port) << std::endl;
  // 设置端口复用
  int reuse = 0;
  reuse =
      setsockopt(m_socketFd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  if (reuse == -1) {
    printError("setsockopt port reuse error...");
  }
  addFdOnEpollTree(epollFd, sockFd, true);
  myUserCnt++; //用户数加1；
  init();
}

void http_conn::init() {}

void http_conn::closeConn(bool real_close) {
  if (real_close && (m_socketFd != -1)) {
    rmFd(epollFd, m_socketFd);
    --myUserCnt;
    m_socketFd = -1;
  }
}

bool http_conn::read() { //读取客户端数据，并存放于缓存区中；
  bzero(&m_read_buff, READ_BUFFER_SIZE);
  while (true) {
    int bytes_read = recv(m_socketFd, m_read_buff, READ_BUFFER_SIZE, 0);
    if (bytes_read == -1) {
      if (errno == EAGAIN || errno == EWOULDBLOCK) {
        break;
      }
      return false;
    } else if (bytes_read == 0) {
      return false;
    }
  }
  return true;
}

bool http_conn::write() {

  sendRespond();
  send404(m_socketFd);
  // int bytes_write = send(m_socketFd, m_read_buff, 20, 0);

  modFd(epollFd, m_socketFd, EPOLLIN);
  return true;
}

void http_conn::process() {
  std::cout << m_read_buff << std::endl;
  modFd(epollFd, m_socketFd, EPOLLOUT);
}

void http_conn::process_read() {
  std::string head(m_read_buff);
  if (head.empty()) {
    show_error(m_socketFd, "read_buff is empty...");
    return;
  }
  // 分析请求：GET /1.txt HTTP/1.1
}

void http_conn::sendRespond() { //服务端响应头；

  char buff[1024] = {0};
  sprintf(buff, "HTTP/1.1 200 OK\r\n");
  sprintf(buff + strlen(buff), "Content-Type: text/html; charset=utf-8\r\n");
  sprintf(buff + strlen(buff), "Content-Length: -1\r\n");
  sprintf(buff + strlen(buff), "Connection: keep-alive\r\n");
  sprintf(buff + strlen(buff), "\r\n");

  int ret = send(m_socketFd, buff, sizeof(buff), 0);
  std::cout << buff << std::endl;
}
